package com.hjqjl.whdemo.feature.feature0.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.blankj.utilcode.util.ToastUtils;
import com.hjqjl.whdemo.R;
import com.hjqjl.whdemo.base.BaseActivity;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TimerActivity extends BaseActivity {
    public static void start(Context context) {
        Intent starter = new Intent(context, TimerActivity.class);
        context.startActivity(starter);
    }

    private Timer timer;
    private TimerTask task;

    private ScheduledExecutorService exec;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timer);
    }

    @Override
    protected void onStart() {
        super.onStart();
        startTimer();
        initTimer();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTimer();
        endExecutorScan();
    }

    /**
     * 启动定时器
     */
    public void startTimer() {
        if (timer == null) {
            timer = new Timer();
        }
        if (task != null) {
            task.cancel();
        }
        task = new TimerTask() {
            @Override
            public void run() {
                //执行定时任务
                ToastUtils.showShort("执行定时任务Timer");
            }
        };
        if (timer != null) {
            timer.schedule(task, 3000, 60000);
        }
    }

    /**
     * 停止定时器 刷新上传数据
     */
    private void stopTimer() {
        if (timer != null) {
            task.cancel();
            timer.cancel();
            timer.purge();
            timer = null;
        }
    }

    private boolean isTimerRun = true;

    private void initTimer() {
        endExecutorScan();
        exec = Executors.newSingleThreadScheduledExecutor();//启动定时线程池
        if (exec != null) {
            exec.scheduleWithFixedDelay(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (isTimerRun) {
                                                    //执行定时任务
                                                    ToastUtils.showShort("执行定时任务ScheduledExecutorService");
                                                }
                                            }
                                        },
                    3, 60, TimeUnit.SECONDS);
        }
    }

    private void endExecutorScan() {
        if (exec != null) {
            isTimerRun = false;
            exec.shutdownNow();
        }
        exec = null;//非单例模式，置空防止重复的任务
    }
}